package com.sq.partner.manager.controller;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayCustomer;
import com.sq.partner.manager.mybatis.model.GatewayPolicy;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.NlifeCov;
import com.sq.partner.manager.mybatis.model.TradPlanBase;
import com.sq.partner.manager.mybatis.model.TreeDto;
import com.sq.partner.manager.service.IGatewayCarPolicyListService;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayCustomerService;
import com.sq.partner.manager.service.IGatewayLifePolicyListService;
import com.sq.partner.manager.service.IGatewayNocarPolicyListService;
import com.sq.partner.manager.service.IGatewayProductService;
import com.sq.partner.manager.service.INlifeProdConfigService;
import com.sq.partner.manager.util.DateUtil;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;

/**
 * 
 * 车险保单查询界面
 * @author menyanlei
 *
 */
@Controller
@RequestMapping(value = "/carPolicyList")
public class CarPolicyListController {
	
	private static Logger logger = LogUtil.getLog(CarPolicyListController.class);
	
	@Resource
	private IGatewayLifePolicyListService lifePolicyListService;

	@Resource
	private IGatewayCarPolicyListService carPolicyListService;

	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	
	@Resource
	private IGatewayProductService productService;
	
	@Resource
	private IGatewayCustomerService customerService;
	
	@Resource
	private INlifeProdConfigService nlifeProdConfigService;
	/***
	 * 车险查询跳转到界面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(Model model){
		return "transManager/carPolicyList";
	}
	
	/**
	 * 查询当前用户的权限机构
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryPrivilegeBranch",method = RequestMethod.POST)
	@ResponseBody
    public Result queryPrivilegeBranch(HttpSession session) throws Exception {
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		logger.info("当前登录用户的userCode为"+user.getUserCode()+",DepartmentStr:"+user.getDepartmentStr());
		
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			return Result.data(lifePolicyListService.queryPrivilegeBranch(user.getDepartmentStr()));
		}
		
		return Result.fail();
    }
	
	/**
	 * 查询传入机构及其子机构
	 * @param size
	 * @param pageIndex
	 * @param deptCode
	 * @param deptCNname
	 * @param parentCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryDeptByDeptAndParentDeptCode",method = RequestMethod.POST)
	@ResponseBody
	public Page<CoreDept> queryDeptByDeptAndParentDeptCode(Integer size,Integer pageIndex,
				String deptCode,String deptCname,String parentDeptCode) throws Exception{
		if(StrUtil.isEmpty(parentDeptCode)){
			throw new AppException("机构不能为空");
		}
		
		Page<CoreDept> page=new Page<CoreDept>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		CoreDept dept=new CoreDept();
		dept.setDeptCode(deptCode);
		dept.setDeptCname(deptCname);
		page.setType(dept);

		return lifePolicyListService.queryDeptPageByDeptAndParentDeptCode(page, parentDeptCode);
	}
	
	/**
	 * 查询人险相关合作伙伴
	 * @param fkAppid
	 * @return List<GatewayChannelInfo>
	 * @throws Exception 
	 */
	@RequestMapping(value = "/queryChannelInfoOfLife",method = RequestMethod.POST)
	public @ResponseBody Page<GatewayChannelInfo> queryChannelInfoOfLife(Integer size,Integer pageIndex,
									String parentDeptCode,String channelName,String channelCode) throws Exception{
		if(StrUtil.isEmpty(parentDeptCode)){
			throw new AppException("机构不能为空");
		}
		
		Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setDeptCode(parentDeptCode);
		channelInfo.setChannelCode(channelCode);
		channelInfo.setChannelName(channelName);
		page.setType(channelInfo);
		return lifePolicyListService.queryChannelInfoPageOfLife(page);
	}
	
	/**
	 * 查询车险相关合作伙伴
	 * @param fkAppid
	 * @return List<GatewayChannelInfo>
	 * @throws Exception 
	 */
	@RequestMapping(value = "/querySubChannelTree",method = RequestMethod.POST)
	@ResponseBody
	public List<TreeDto> querySubChannelTree(String parentChannelCode) throws Exception{
		if(StrUtil.isEmpty(parentChannelCode)){
			throw new AppException("合作伙伴代码不能为空");
		}
		
		return lifePolicyListService.querySubChannelTreeByParentChannelCode(parentChannelCode);
	}
	
	/**
	 * 分页条件查询车险保单
	 * @param session
	 * @param pageIndex
	 * @param policy
	 * @param privilegeBranch
	 * @param polSubDateBegin
	 * @param polSubDateEnd
	 * @param polBeginDateBegin
	 * @param polBeginDateEnd
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryCarPolicyPageByCriteria")
	@ResponseBody
    public Page queryCarPolicyPageByCriteria(HttpSession session, Integer pageIndex,
    			GatewayPolicy policy,String privilegeBranch,String polSubDateBegin,
    			String polSubDateEnd,String polBeginDateBegin,String polBeginDateEnd) throws Exception {
		
		@SuppressWarnings("rawtypes")
		Page page = beforeQueryNocarPolicyPageByCriteria(session, pageIndex, policy, privilegeBranch,polSubDateBegin, polSubDateEnd, polBeginDateBegin, polBeginDateEnd);
		if("error".equals(page.getResult()) || "noChannelInfo".equals(page.getResult())){
			return page;
		}
		return carPolicyListService.queryCarPolicyPageByCriteria(page);
    }
	
	/**
	 * 下载财险保单信息
	 * @param session
	 * @param response
	 * @param policy
	 * @param privilegeBranch
	 * @param polSubDateBegin   
	 * @param polSubDateEnd
	 * @param polBeginDateBegin
	 * @param polBeginDateEnd
	 * @throws Exception
	 */
	@RequestMapping(value = "/downloadCarPolicyFileByCriteria")
    public void downloadCarPolicyFileByCriteria(HttpSession session,HttpServletResponse response, 
    			GatewayPolicy policy,String privilegeBranch,String polSubDateBegin,
    			String polSubDateEnd,String polBeginDateBegin,String polBeginDateEnd) throws Exception {
		
		Page page = beforeQueryNocarPolicyPageByCriteria(session, -1, policy, privilegeBranch,polSubDateBegin, polSubDateEnd, polBeginDateBegin, polBeginDateEnd);
		
		Map<String,Object> map = (Map<String, Object>) page.getType();
		//TODO
		List<Map<String, Object>> carPolicyList = carPolicyListService.queryCarPolicyListByCriteria(map);
		carPolicyListService.downloadCarPolicyFile(carPolicyList, response);
    }
	
	
	/**
	 * 车险保单查询和保单信息下载前进行验证
	 * @param session
	 * @param pageIndex
	 * @param policy
	 * @param privilegeBranch
	 * @param polSubDateBegin
	 * @param polSubDateEnd
	 * @param polBeginDateBegin
	 * @param polBeginDateEnd
	 * @return
	 * @throws Exception
	 */
	public Page beforeQueryNocarPolicyPageByCriteria(HttpSession session, Integer pageIndex,
			GatewayPolicy policy,String privilegeBranch,String polSubDateBegin,
			String polSubDateEnd,String polBeginDateBegin,String polBeginDateEnd) throws Exception{
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		
		Page page = new Page();
		Map<String,Object> map = new HashMap<String, Object>();
		if(pageIndex != -1){
			page.setCurrent(pageIndex);
			map = SqlUtil.buildPageMap(page);
		}
		//机构验证
		if(StrUtil.isEmpty(privilegeBranch)){
			throw new AppException("系统异常：机构不能为空");
		}else{
			if(!(channelInfoConfigService.checkIsHasPrivilege(session, privilegeBranch))){
				throw new AppException("用户权限不足");
			}	
		}
		map.put("privilegeBranch",privilegeBranch);
		
		map.put("dptCode", policy.getDptCde());
	
		//保单提交日期
		if(StrUtil.isNotEmpty(polSubDateBegin)){
			polSubDateBegin = polSubDateBegin + "00:00:00";
		}
		if(StrUtil.isNotEmpty(polSubDateEnd)){
			polSubDateEnd = polSubDateEnd + "23:59:59";
		}
		
		map.put("polSubDateBegin", polSubDateBegin);
		map.put("polSubDateEnd", polSubDateEnd);
		
		//保单生效日期
		if(StrUtil.isNotEmpty(polBeginDateBegin)){
			polBeginDateBegin = polBeginDateBegin + " 00:00:00";
		}
		if(StrUtil.isNotEmpty(polBeginDateEnd)){
			polBeginDateEnd = polBeginDateEnd + " 23:59:59";
		}
		
		map.put("polBeginDateBegin", polBeginDateBegin);
		map.put("polBeginDateEnd", polBeginDateEnd);
		
		
		//合作伙伴代码
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setDeptCode(privilegeBranch);
		List<Map> channelInfoList = carPolicyListService.queryChannelListOfNocar(channelInfo,"car");
		if(null == channelInfoList || channelInfoList.size() == 0){
			page.setResult("noChannelInfo");
			return page;
		}
		
		String channelCodeStr;
		if(StrUtil.isEmpty(policy.getPartnerNo())){
			channelCodeStr = "";
		}else{
			List<String> channelCodeList = new ArrayList<String>();
			for (Map m : channelInfoList) {
				channelCodeList.add(m.get("CHANNELCODE").toString());
			}
			if(!channelCodeList.contains(policy.getPartnerNo())){
				page.setResult("error");
				page.setMessage("合作伙伴["+policy.getPartnerNo()+"]没有权限执行此操作或者没有保单");
				return page;
			}
			channelCodeStr="'"+policy.getPartnerNo()+"'";
		}	
		map.put("channelCodeStr", channelCodeStr);
		map.put("isHq", 'N');
		//合作伙伴子机构
		if(StrUtil.isNotEmpty(policy.getPartnerSubCode()) && StrUtil.isEmpty(policy.getPartnerNo())){
			page.setResult("error");
			page.setMessage("合作伙伴子机构不为空，合作伙伴不允许为空");
			return page;
		}else if("00".equals(privilegeBranch)){
			map.put("isHq", 'Y');
		}
		map.put("partnerSubCode", policy.getPartnerSubCode());
		
		map.put("polno", policy.getPolno());
		map.put("stateId", policy.getStateId());
		if(StrUtil.isEmpty(policy.getLicenseno())){
			map.put("licenseno", null);
		}else{
			map.put("licenseno", "%"+policy.getLicenseno()+"%");
		}
		
		map.put("tradProdType", policy.getTradProdType());
		map.put("spical1", policy.getSpical1());
		
		page.setType(map);
		return page;
	}
}
